package com.caijin.web.controller.testredis;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.caijin.common.core.domain.Result;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class CategoryApi {

    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation(value = "创建菜单项")
    @PostMapping("/create")
    @ResponseBody
    public Result add(@RequestBody Category category) {
        Result result = new Result();
        result.success(true);
        redisTemplate.opsForList().leftPush("categoryList4", category);
        result.data("data",category);
        return result;
    }
//
//    @ApiOperation(value = "获取菜单信息")
//    @GetMapping("/queryAll")
//    @ResponseBody
//    public Result queryAll() {
//        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//        redisTemplate.setKeySerializer(new StringRedisSerializer());
//        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
//        this.redisTemplate = redisTemplate;
//        Result result = new Result();
//        result.success(true);
//redisTemplate.opsForValue().set();
//
//        // 查询所有的类目数据
//        List<Category> categoryDatas = redisTemplate.opsForList().range("categoryList4", 0, -1);
//
//        //处理父子类目关系
//        List<Category> allFirstCats = handleParentData(categoryDatas);
//        result.data("data",allFirstCats);
//        return result;
//    }

    @ApiOperation(value = "获取某一菜单信息")
    @GetMapping("/get")
    @ResponseBody
    public Result get(@RequestParam("id")String id){
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        this.redisTemplate = redisTemplate;
        // 查询所有的类目数据
        List<Category> categoryDatas = redisTemplate.opsForList().range("categoryList4", 0, -1);

        //处理父子类目关系
        List<Category> allFirstCats = handleParentData(categoryDatas);
        Result result = new Result();
        result.success(true);
        allFirstCats.forEach(category -> {
            if(id.equals(category.getId())){
                result.data("data",category);
            }
        });
        return result;
    }

    private List<Category> handleParentData(List<Category> categoryDatas) {
        if (CollectionUtils.isEmpty(categoryDatas)) {
            // 防止空指针异常，返回一个没有元素的 List
            return new ArrayList<>();
        }

        // 存储类目的 Map
        Map<String, Category> catsMap = new HashMap<>();
        //初始化一个虚拟根节点，其subCategoryList就是所有的一级类目
        catsMap.put("0", new Category());

        categoryDatas = JSON.parseArray(JSON.toJSONString(categoryDatas),Category.class);

        categoryDatas.stream().forEach(category -> {

            // 全部放入Map
            catsMap.put(category.getId(), category);
        });

        // 再次遍历模型，处理父子关系
        categoryDatas.forEach(category -> {
            // 得到父实例
            String pId = category.getParentCategoryId();

            // 没有父类目 Id，当做 0 处理，作为虚拟根节点的子类目，就是所有的一级类目
            if (StringUtils.isBlank(pId)) {
                pId = "0";
            }

            Category parentCat = catsMap.get(pId);
            if (parentCat != null) {
                // 未初始化则初始化
                if (parentCat.getSubCategoryList() == null) {
                    parentCat.setSubCategoryList(new ArrayList<>());
                }

                // 当前的类目对象放入类类目的 subCategoryList
                parentCat.getSubCategoryList().add(category);
            }
        });

        List<Category> allFirstCats = catsMap.get("0").getSubCategoryList();

        return allFirstCats;
    }

}

